package com.ujiaoyu.security;

import com.ujiaoyu.security.jwt.JwtConfig;
import com.ujiaoyu.security.jwt.TokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final CorsFilter corsFilter;
    private final AuthEntryPointImpl authEntryPoint;
    private final AccessDeniedHandlerImpl accessDeniedHandler;
    private final TokenProvider tokenProvider;
    private final UserDetailServiceImpl userDetailsService;



    public WebSecurityConfig(CorsFilter corsFilter, AuthEntryPointImpl authEntryPoint, AccessDeniedHandlerImpl accessDeniedHandler, TokenProvider tokenProvider, UserDetailServiceImpl userDetailsService) {
        this.corsFilter = corsFilter;
        this.authEntryPoint = authEntryPoint;
        this.accessDeniedHandler = accessDeniedHandler;
        this.tokenProvider = tokenProvider;
        this.userDetailsService = userDetailsService;
    }


    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder builder) throws Exception {

        builder.userDetailsService(this.userDetailsService)
                .passwordEncoder(passwordEncoder());
    }



    @Bean
    public PasswordEncoder passwordEncoder(){
       return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
         //配置忽略哪些资源不受安全框架过滤
        web.ignoring()
                .antMatchers(HttpMethod.OPTIONS,"/**")
                .antMatchers(
                        "/",
                        "/*.html",
                        "/**/*.html",
                        "/favicon.ico",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-ui/**"

                );

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable() //禁用跨域攻击
        //允许跨域的Filter 加在     UsernamePasswordAuthenticationFilter 之前
        .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)

        //认证与授权的异常处理
        .exceptionHandling()
        .authenticationEntryPoint(authEntryPoint)
        .accessDeniedHandler(accessDeniedHandler)


        //无需session
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)



        //认证授权的规则

        .and()
        .authorizeRequests()
        .antMatchers("/api/user/signIn").permitAll()
        .antMatchers("/api/user/signUp").permitAll()
//        .antMatchers("/api/user/getUserInfo").hasAnyAuthority("ROLE_USER")
        .anyRequest().permitAll()

        //JWT Filter
        .and()
        .apply(new JwtConfig(tokenProvider));

    }

}
